﻿
class Player extends createjs.Bitmap {

    velocityX: number;
    velocityY: number;
    onGround: boolean;
    doubleJump: boolean;
    life: number;

    constructor(image: string) {
        super(image);
        this.velocityX = 0;
        this.velocityY = 12;
        this.name = "Hero";
        this.snapToPixel = true;
        this.onGround = false;
        this.doubleJump = false;
        this.life = 1;
    }

    reset() {
        this.y = 0;
        this.x = 50 / 1.25;
        this.velocityY = -10;
    }

    jump() {
        if (this.onGround) {
            this.velocityY = -17;
            this.onGround = false;
            this.doubleJump = true;
        }
        else if (this.doubleJump) {
            this.velocityY = -17;
            this.doubleJump = false;
        }
    }

    tick() {
        this.velocityY += 1;

        var c = 0,
            cc = 0,
            addY = this.velocityY,
            bounds = this.getBounds(),
            cbounds: createjs.Rectangle,
            collision = null,
            collideables: Block[] = blocks;

        // for each collideable object we will check for an intersection
        // of the player's future position's bounding - rectangle
        while (!collision && cc < collideables.length) {
            cbounds = collideables[cc].getBounds();
            if (collideables[cc].isVisible) {
                collision = calculateIntersection(bounds, cbounds, 0, addY);
            }

            // if the was no collision but the player got into the other side of an object
            // (e.g. high velocity) then we will detect it here
            // and adjust the velocity to prevent the player to go through objects
            if (!collision && collideables[cc].isVisible) {
                if ((bounds.y < cbounds.y && bounds.y + addY > cbounds.y)
                    || (bounds.y > cbounds.y && bounds.y + addY < cbounds.y)) {
                    addY = cbounds.y - bounds.y;
                }
                else {
                    cc++;
                }
            }
        }

        if (!collision) {
            this.y += addY;
            if (this.onGround) {
                this.onGround = false;
                this.doubleJump = true;
            }
        }
        else {
            this.y += addY - collision.height;
            if (addY > 0) {
                this.onGround = true;
                this.doubleJump = false;
            }
            this.velocityY = 0;
        }
    }
} 